package com.tsdykj.peng.diary;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tsdykj.peng.diary.function.DiaryApplication;
import com.tsdykj.peng.diary.function.GetDataListener;
import com.tsdykj.peng.diary.function.HttpConnectionTestTask;
import com.tsdykj.peng.diary.function.PathManager;
import com.tsdykj.peng.diary.function.RequestListener;
import com.tsdykj.peng.diary.function.VolleyStringRequestAsync;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class person_activity extends Activity {

    private static final String TAG = "person_activity";

    private EditText edtUserId;
    private EditText edtName;
    private AutoCompleteTextView edtMail;
    private EditText edtMailPwd;
    private AutoCompleteTextView zkMail;
    private EditText edtPrefixDepart;
    private AutoCompleteTextView edtMail2;
    private EditText edtDepart;

    private ProgressDialog progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_person);

        edtUserId = (EditText) findViewById(R.id._edt_person_id);
        edtName = (EditText) findViewById(R.id._edt_person_name);
        edtMail = (AutoCompleteTextView) findViewById(R.id._edt_mail);
        edtMailPwd = (EditText) findViewById(R.id._edt_mailpwd);
        zkMail = (AutoCompleteTextView) findViewById(R.id._edt_zk_mail);
        edtMail2 = (AutoCompleteTextView) findViewById(R.id._edt_mail2);
        edtPrefixDepart = (EditText) findViewById(R.id._edt_prefix_depart);
        edtDepart = (EditText) findViewById(R.id._edt_depart);

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        DiaryApplication.getInstance().addActivity(this);
    }

    @Override
    protected void onStart() {

        new HttpConnectionTestTask(new GetDataListener() {
            @Override
            public void GetData(boolean online) {
                if (online) {
                    getUserData();
                } else {
                    Toast.makeText(person_activity.this, R.string.serveroffline, Toast.LENGTH_SHORT).show();
                }
            }
        }).execute();

        String url = PathManager.Host + "settings/zk_mail";
        new VolleyStringRequestAsync(person_activity.this, url, new RequestListener() {
            @Override
            public void ProcessData(String data) {
                zkMail.setText(data);
            }
        }).Execute();

        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_person_activity, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_person_save:
                saveUserData();
                return true;
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }


    }

    protected void getUserData() {

        if (PathManager.CURRENT_USER_OBJECT_ID == null || PathManager.CURRENT_USER_OBJECT_ID.length() <= 0) {

            return;
        }

        progressDialog = ProgressDialog.show(this, getString(R.string.please_wait), getString(R.string.getting_data), true);

        RequestQueue requestQueue = Volley.newRequestQueue(person_activity.this);

        String url = PathManager.Host + "users";
        url += "/" + PathManager.CURRENT_USER_OBJECT_ID;

        Log.d(TAG, url);
        Log.d(TAG, PathManager.CURRENT_USER_OBJECT_ID);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                Log.d("getUserData", response.toString());

                try {
                    edtUserId.setText(response.get("id").toString());
                    edtName.setText(response.get("name").toString());
                    edtMail.setText(response.get("mail").toString());
                    edtMailPwd.setText(response.get("mailpwd").toString());
                    edtMail2.setText(response.get("mail2").toString());
                    edtPrefixDepart.setText(response.get("prefix_depart").toString());
                    edtDepart.setText(response.get("depart").toString());

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (progressDialog != null) progressDialog.dismiss();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (progressDialog != null) progressDialog.dismiss();
                String error_msg = (error.getMessage() == null || error.getMessage().equals("")) ? error.toString() : error.getMessage();
                VolleyLog.d(TAG, "Error: " + error_msg);
                Toast.makeText(getApplicationContext(),
                        error_msg, Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);
    }


    protected void saveUserData() {

        progressDialog = ProgressDialog.show(this, getString(R.string.please_wait), getString(R.string.save_user_data), true);

        RequestQueue requestQueue = Volley.newRequestQueue(person_activity.this);

        int method = Request.Method.POST;
        String url = PathManager.Host + "users";

        Log.d(TAG, url);
        Log.d(TAG, PathManager.CURRENT_USER_OBJECT_ID);

        StringRequest request = new StringRequest(method, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("res", response);

                try {
                    JSONObject obj = new JSONObject(response);

                    PathManager.CURRENT_USER_OBJECT_ID = obj.getString("_id");
                    PathManager.CURRENT_USER_ID = obj.getString("id");

                    SharedPreferences sp = getApplicationContext().getSharedPreferences("dyjob", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("user_object_id", PathManager.CURRENT_USER_OBJECT_ID);
                    editor.putString("user_id", PathManager.CURRENT_USER_ID);
                    editor.apply();

                    if (progressDialog != null) progressDialog.dismiss();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("userId", PathManager.CURRENT_USER_OBJECT_ID);
                map.put("id", edtUserId.getText().toString());
                map.put("name", edtName.getText().toString());
                map.put("mail", edtMail.getText().toString());
                map.put("mailpwd", edtMailPwd.getText().toString());
                map.put("mail2", edtMail2.getText().toString());
                map.put("prefix_depart", edtPrefixDepart.getText().toString());
                map.put("depart", edtDepart.getText().toString());

                return map;
            }
        };
        requestQueue.add(request);
    }
}
